package cn.snmp.mutual.nms;

public class SnmpBitstring extends SnmpVar
{
    static final byte[] s_emptyString;
    byte[] byteValue;
    String value;
    
    SnmpBitstring() {
        this.byteValue = SnmpBitstring.s_emptyString;
        this.value = null;
    }
    
    public SnmpBitstring(final String s) {
        this.byteValue = SnmpBitstring.s_emptyString;
        this.value = null;
        this.Type = 3;
        if (s == null) {
            return;
        }
        this.value = s;
        final int i = this.value.length();
        this.byteValue = this.value.getBytes();
    }
    
    public SnmpBitstring(final byte[] bytes) {
        this.byteValue = SnmpBitstring.s_emptyString;
        this.value = null;
        this.Type = 3;
        if (bytes == null) {
            return;
        }
        System.arraycopy(bytes, 0, this.byteValue = new byte[bytes.length], 0, bytes.length);
    }
    
    public SnmpBitstring(final byte[] bytes, final int i) throws SnmpException {
        this.byteValue = SnmpBitstring.s_emptyString;
        this.value = null;
        if (bytes.length * 8 < i) {
            throw new SnmpException(SnmpUtils.getString("Size less than array limits."));
        }
        final int j = i % 8;
        final int k = i / 8 + ((j > 0) ? 1 : 0);
        (this.byteValue = new byte[k + 1])[0] = (byte)(8 - j & 0x7);
        System.arraycopy(bytes, 0, this.byteValue, 1, k);
    }
    
    @Override
    int encode(final byte[] bytes, final int i) throws ArrayIndexOutOfBoundsException {
        if (this.byteValue.length < 1 || this.byteValue[0] < 0 || this.byteValue[0] > 7) {}
        return ASNTypes.encodeOctets(bytes, i, this.byteValue, 0, this.byteValue.length, 3);
    }
    
    @Override
    public Object getVarObject() {
        return this.toValue();
    }
    
    static SnmpVar newInstance(final byte[] bytes) {
        final SnmpBitstring snmpbitstring = new SnmpBitstring();
        snmpbitstring.Type = 3;
        snmpbitstring.byteValue = bytes;
        return snmpbitstring;
    }
    
    @Override
    public byte[] toBytes() {
        final byte[] bytes = new byte[this.byteValue.length];
        System.arraycopy(this.byteValue, 0, bytes, 0, this.byteValue.length);
        return bytes;
    }
    
    @Override
    public String toString() {
        if (this.value == null) {
            this.value = new String(this.byteValue);
        }
        return this.value;
    }
    
    @Override
    public String toTagString() {
        return "BITSTRING : " + this.toString();
    }
    
    @Override
    public Object toValue() {
        return this.toString();
    }
    
    static {
        s_emptyString = new byte[0];
    }
}
